package com.orivon.mob.hook.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.orivon.mob.hook.DeviceInfo;
import com.orivon.mob.hook.HookApplication;
import com.orivon.mob.hook.R;
import com.orivon.mob.hook.bean.SupportVer;
import com.orivon.mob.hook.helper.DaoHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindCallback;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

public class MainActivity extends AppCompatActivity {
    ListView diceList;
    List<CharSequence> diceListData;
    DiceListAdapter diceListAdapter;
    AlertDialog.Builder builder;
    AlertDialog dialog;
    DeviceInfo deviceInfo;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        check(HookApplication.getInstance().getDeviceInfo().getImei());

    }

    private void initView() {
        diceList = (ListView) findViewById(R.id.diceList);
        diceList.setAdapter(diceListAdapter);
    }


    protected void saveDiceNum(int position) {
        ContentValues values = new ContentValues();
        values.put("dice_num", position);
        DaoHandler.getInstance(context).add(values);
    }


    public void addList(View v) {
        saveDiceNum(Integer.parseInt((String) ((Button) v).getText()) - 1);
        diceListData = DaoHandler.getInstance(context).getNumList();
        diceListAdapter.notifyDataSetChanged();
    }

    private class DiceListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return diceListData.size();
        }

        @Override
        public Object getItem(int position) {
            return diceListData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textCount;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_dice_layout, null);
                textCount = (TextView) convertView.findViewById(R.id.textCount);
                convertView.setTag(textCount);
            } else {
                textCount = (TextView) convertView.getTag();
            }
            textCount.setText(diceListData.get(diceListData.size() - 1 - position));
            return convertView;
        }
    }


    @Override
    protected void onRestart() {
        diceListData = DaoHandler.getInstance(context).getNumList();
        diceListAdapter.notifyDataSetChanged();
        super.onRestart();
    }


    public void check(String imei) {
        showDialog("校验中...");
        BmobQuery<DeviceInfo> query = new BmobQuery<DeviceInfo>();
        query.setLimit(1);
        query.addWhereEqualTo("imei", imei);
        query.findObjects(this, new FindListener<DeviceInfo>() {
            @Override
            public void onSuccess(List<DeviceInfo> list) {
                if (list.size() > 0) {
                    if (list.get(0).getStatues().equals("0")) {
                        if (list.get(0).getMac().equals(HookApplication.getInstance().getDeviceInfo().getMac())) {
                            hideDialog();
                            setContentView(R.layout.activity_main);
                            diceListData = new ArrayList<>();
                            diceListAdapter = new DiceListAdapter();
                            initView();
                            diceListData = DaoHandler.getInstance(context).getNumList();
                            diceListAdapter.notifyDataSetChanged();
                        } else {
                            showDialogWithButton("你的设备没有权限使用！！！\n" + "傻逼！以为换个模拟器就可以啊？！");
                        }
                    } else {
                        showDialogWithButton("你的设备没有权限使用！！！\n" + list.get(0).getMsg());
                    }

                } else {
                    showDialogWithButton("用户不存在！", "需要注册后才能使用", "立即注册", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            HookApplication.getInstance().getDeviceInfo().save(MainActivity.this, new SaveListener() {
                                @Override
                                public void onSuccess() {
                                    check(HookApplication.getInstance().getDeviceInfo().getImei());
                                }

                                @Override
                                public void onFailure(int i, String s) {
                                    showDialog("注册失败");
                                }
                            });
                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {
                showDialogWithButton("校验失败！", s);
            }
        });


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DeviceInfo event) {
        deviceInfo = event;
        check(event.getImei());
    }

    @Override
    protected void onStart() {
        EventBus.getDefault().register(this);
        super.onStart();
    }


    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    public void showDialog(String msg) {

        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }

        if (builder == null) {
            builder = new AlertDialog.Builder(this);
        }
        builder.setTitle("提示:");
        builder.setMessage(msg);
        builder.setCancelable(false);
        dialog = builder.create();
        dialog.show();
    }

    public void showDialogWithButton(String msg) {

        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }

        if (builder == null) {
            builder = new AlertDialog.Builder(this);
        }
        builder.setTitle("提示:");
        builder.setMessage(msg);
        builder.setCancelable(false);
        builder.setPositiveButton("重新验证", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                check(HookApplication.getInstance().getDeviceInfo().getImei());
            }
        });
        builder.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                System.exit(0);
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    public void showDialogWithButton(String title, String msg) {

        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }

        if (builder == null) {
            builder = new AlertDialog.Builder(this);
        }
        builder.setTitle(title);
        builder.setMessage(msg);
        builder.setCancelable(false);
        builder.setPositiveButton("重新验证", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                check(HookApplication.getInstance().getDeviceInfo().getImei());
            }
        });
        builder.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    public void showDialogWithButton(String title, String msg, String btnText, DialogInterface.OnClickListener listener) {

        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }

        if (builder == null) {
            builder = new AlertDialog.Builder(this);
        }
        builder.setTitle(title);
        builder.setMessage(msg);
        builder.setCancelable(false);
        builder.setPositiveButton(btnText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                check(HookApplication.getInstance().getDeviceInfo().getImei());
            }
        });
        builder.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        dialog = builder.create();
        dialog.show();
    }


    public void hideDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.reshVer:
                getVer(new FindListener<SupportVer>() {
                    @Override
                    public void onSuccess(List<SupportVer> list) {
                        DaoHandler.getInstance(context).saveSupVer(list);
                    }

                    @Override
                    public void onError(int i, String s) {
                        System.out.println("save error");
                    }
                });
                break;

            case R.id.info:

                break;
            case R.id.clear:
                DaoHandler.getInstance(context).clearData();
                diceListData = DaoHandler.getInstance(context).getNumList();
                diceListAdapter.notifyDataSetChanged();
                break;
        }
        return true;
    }

    public void getVer(FindListener<SupportVer> listener) {
        BmobQuery<SupportVer> query = new BmobQuery<>();
        query.findObjects(MainActivity.this, listener);
    }

}
